﻿using Microsoft.AspNetCore.Authorization;
using System;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity;
using XfTech.SmartTms.DomainServices;
using XfTech.SmartTms.Entities.Issues;
using XfTech.SmartTms.Issues.Dtos;
using XfTech.SmartTms.Repositories;
using XfTech.SmartTms.Specifications;

namespace XfTech.SmartTms.Issues
{
    /// <summary>
    /// 问题管理模块 应用服务
    /// </summary>
    [Authorize]
    public class IssueAppService : ApplicationService, IIssueAppService
    {
        private readonly IssueManager _issueManager;
        private readonly IIssueRepository _issueRepository;
        private readonly IRepository<IdentityUser, Guid> _userRepository;

        public IssueAppService(IssueManager issueManager,
                               IIssueRepository issueRepository,
                               IRepository<IdentityUser, Guid> userRepository)
        {
            _issueRepository = issueRepository;
            _issueManager = issueManager;
            _userRepository = userRepository;
        }

        /// <summary>
        /// 给问题分配负责人
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task AssignAsync(IssueAssignDto input)
        {
            var issue = await _issueRepository.GetAsync(input.IssueId);
            var user = await _userRepository.GetAsync(input.UserId);

            await _issueManager.AssignToAsync(issue, user);

            await _issueRepository.UpdateAsync(issue);
        }

        /// <summary>
        /// 创建问题
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IssueShowDto> CreateIssueAsync(IssueCreateDto input)
        {
            //创建一个问题
            Issue issue = new Issue(GuidGenerator.Create(),
                input.RepositoryId,
                input.Title,
                input.Text,
                input.AssignedUserId);

            issue.SetLabels(input.LabelIds); //设置标签

            //调用自定义仓储的添加方法 添加到数据库
            Issue result = await _issueRepository.CreateIssuesAsync(issue);
            //或调用ABP的泛型仓储基类的Insert方法
            //Issue result = await _issueRepository.InsertAsync(issue);

            return ObjectMapper.Map<Issue, IssueShowDto>(result);
        }

        public async Task DoItAsync()
        {
            var issues = await _issueRepository.GetIssuesAsync(
                new InActiveIssueSpecification()
            );
        }
    }

}
